/*
 * Copyright: Copyright (c) 2014-2015 ZhongDaMen,Inc.All Rights Reserved. 
 * Company:中大门网络科技有限公司
 */

package com.sc.web.common;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.data.DataUtil;
import com.sc.util.data.FileUtil;
import com.sc.util.exception.ExceptionEnum;

/**
 * <h1>普通图片上传控制器</h1>
 * 
 * @ClassName: CommenImageController
 * @Description:
 * @author Zdm-lifang
 * @date 2015年10月9日 下午4:04:17
 *
 */
@Controller
@RequestMapping("/commonImage")
public class CommenImageController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private HttpSession session;
	
	/**
	 * <h2>商品相册图片上传</h2>
	 * 
	 * @Title: uploadGoodsPhoto
	 * @param request
	 * @param session
	 * @param file
	 * @return Map<String, Object>
	 * @throws Exception
	 */
	@RequestMapping(value = "/uploadGoodsPhoto", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> uploadGoodsPhoto(HttpServletRequest request)throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> dataMap = new HashMap<String, Object>();
		try {
			String url = FileUtil.upload(request, "file", "goods", ConfigBeanAdapter.fileSaveAddress);
			
			DataUtil.handleResultMap(resultMap,ExceptionEnum.DATA_SUCCESS);
			
			dataMap.put("url", url);
		} catch (Exception e) {
			DataUtil.handleResultMap(resultMap,ExceptionEnum.DATA_INSERT);
			logger.error("图片保存失败！" + e);
		}
		resultMap.put("data", dataMap);

		return resultMap;
	}
	
	/**
	 * UEditor上传文件使用
	 * @param upfile
	 * @param request
	 * @return Map<String,String>
	 * @throws IOException
	 */
	/*@RequestMapping("uploadImage")
	@ResponseBody	//这里upfile是config.json中图片提交的表单名称
	public Map<String,String> uploadImage(@RequestParam("upfile") CommonsMultipartFile upfile, HttpServletRequest request) throws IOException{  
		//返回结果信息(UEditor需要)
		Map<String,String> map = new HashMap<String,String >();
		if(!upfile.isEmpty()){ 
			//文件原名称
			String oriName=upfile.getOriginalFilename();
		    //为了避免重复简单处理
			String type = oriName.substring(oriName.lastIndexOf(".")).toLowerCase();
			String filename = UUID.randomUUID().toString()+type;
			
			//上传位置路径
			String path = uploadPath+"goods/"+filename;

			//按照路径新建文件
			File newFile = new File(path);

			//复制
			FileCopyUtils.copy(upfile.getBytes(), newFile);
			
			//是否上传成功
			map.put("state", "SUCCESS");
			//现在文件名称
	     	map.put("title", filename);
	     	//文件原名称 
	     	map.put("original", oriName);
	     	//文件类型 .+后缀名
	     	map.put("type", type);
	     	//文件路径
	     	map.put("url", "/goods/"+filename);
	     	//文件大小（字节数）
	     	map.put("size", upfile.getSize()+"");
        }

        return map;
	}*/
	
	/**
	 * KindEditor上传文件使用
	 * @param upfile
	 * @param request
	 * @return Map<String,String>
	 * @throws IOException
	 */
	@RequestMapping(value = "uploadImage/{module}", method = RequestMethod.POST)
	@ResponseBody	//这里imgFile是图片提交的表单名称
	public Map<String,Object> uploadImage(@RequestParam("imgFile") CommonsMultipartFile file, @PathVariable String module, HttpServletRequest request) throws IOException{  
		//返回结果信息(KindEditor需要)
		Map<String,Object> resultMap = new HashMap<String,Object>();
		if(!file.isEmpty()){
			try{
				//文件原名称
				String oriName=file.getOriginalFilename();
			    //为了避免重复简单处理
				String type = oriName.substring(oriName.lastIndexOf(".")).toLowerCase();
				String filename = UUID.randomUUID().toString()+type;
				
				//上传位置路径
				String folderPath=ConfigBeanAdapter.fileSaveAddress+module;
				File f = new File(folderPath);
			    boolean result = f.exists();
		        if (!result) {
		            result = f.mkdirs();
		        }
				String path = ConfigBeanAdapter.fileSaveAddress+module+"/"+filename;
	
				//按照路径新建文件
				File newFile = new File(path);
	
				//复制
				FileCopyUtils.copy(file.getBytes(), newFile);
				
		     	//文件路径
				resultMap.put("url", ConfigBeanAdapter.fileAccessAddress+module+"/"+filename);
				
				resultMap.put("error", 0);
				resultMap.put("message", "上传成功！");
				logger.info("KindEditor上传图片成功！");
			}catch(Exception e){
				e.printStackTrace();
				resultMap.put("error", 1);
				resultMap.put("message", "上传失败！");
				logger.error("KindEditor上传图片失败！" + e);
			}
			
        }

        return resultMap;
	}
	
}
